﻿using System.Collections.Generic;
using System.IO;
using System.Security.Claims;
using Authorize.Core.Authentication;
using Authorize.Core.Authentication.WeChat;
using Authorize.Core.Extensions;
using Authorize.Core.Store;
using Authorize.Core.Web;
using Authorize.Host.App_Data;
using IdentityServer4;
using IdentityServer4.Models;
using IdentityServer4.Test;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Rewrite;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Authorize.Host
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
            PrefixUrl.PublicOrigin = Configuration["PublicOrigin"];
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddIdentityServer(options =>
                {
                    options.PublicOrigin = Configuration["PublicOrigin"];
                })
                .AddSigningCredential(IdentityServerBuilderExtensionsCrypto.CreateRsaSecurityKey())
                .AddClientSource()
                .AddResourceStore<ResourceStore>()
                .AddProfileService<CustomProfileService>();
            services.AddAuthentication()
                .AddWeChat("Wechat", "微信", options =>
                {
                    options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;

                    options.AppId = Configuration["Authentication:Wechat:AppId"];
                    options.AppSecret = Configuration["Authentication:Wechat:AppSecret"];
                    options.PublicOrigin = PrefixUrl.PublicOrigin;
                });           
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            // app.UseMiddleware<BaseUrlMiddleware>(Configuration["PublicOrigin"]);

            app.UseIdentityServer();
            app.UseStaticFiles();
            app.UseMvcWithDefaultRoute();            
            app.UseMvc();

            Application.AutoMapper.InitAutoMapper();
        }
    }
}
